﻿chrome.extension.sendRequest({action : 'getOptions', title:document.title},function(response) {
var isAdmin = $('textarea').length > 0;
var isProfilePage = document.URL.indexOf('/profile')>0;
var opt = response;
var muteTags = opt.muteTags;
var version = opt.version;

function getRightNavs(ver){
    var navs = [];
    if(ver == '3'){
        navs = $('.MIB_mblogbgl').find('.mainR>div:gt(0)');
    }
    else if(ver.indexOf('3.') > -1){
        navs=$("div.W_main_r").children('div');
    }
    else{
        navs=$('div.W_main_r').children('div');
    }
    
    return navs;
}


		function getFeeds(ver)
	    {
            var navs = [];
            if(ver == '3'){
                navs = $('#feed_list').children('li.MIB_linedot_l');
            }
            else if(ver.indexOf('3.') > -1){
                navs=$("div.feed_lists").children('dl');
            }
            else{
                navs=$("div.feed_lists").children('dl');
            }
            
            return navs;
	    }

//隐藏右边
if(opt && opt.options && opt.options.hide)
{
    if(isAdmin || isProfilePage)
    {
        var rightNavs = getRightNavs(version);
        var hide = isAdmin ? opt.hide.admin.right : opt.hide.profile.right;
        rightNavs.each(function(index)
        {
            if($.inArray(index, hide) > -1)
            {
                $(this).css('display', 'none');
            }
        });
    }
}

//显示大图
if(opt.options.bigPic === true)
{
	if(version!= '3')
  {
  	$('dd[node-type=feed_list_media_prev], ul[node-type=feed_list_media_prev]').each(function(){
  		expandImg(this);
  	});
  	

      setInterval(function(){
          $('dd[node-type=feed_list_media_prev], ul[node-type=feed_list_media_prev]').each(function(){
			expandImg(this);
		});
	}, 200);
      
  	function expandImg(preview)
  	{
  		var img = $(preview).find('img.bigcursor');
  		var src = $(img).attr('src');
  		var direct = $(this).attr("tagName") == 'ul';
  		if(src)
  		{
  			var midSrc = src.replace("/thumbnail/", "/bmiddle/");
  			var bigSrc = src.replace("/thumbnail/", "/large/");
  			$(preview).hide();
  			var expand = $(preview).next();
  			var html = [];
  			if(expand && expand.css('display') == 'none')
  			{
  				if(direct){html.push('<dd class="expand">');}
  				html.push(['<p class="W_no_border"><a action-type="feed_list_media_toSmall" href="javascript:void(0);" class="retract">收起</a><i class="W_vline">|</i><a href="', bigSrc, '" target="_blank" class="show_big">查看大图</a><i class="W_vline">|</i><a action-type="feed_list_media_toLeft" href="javascript:void(0);" class="turn_left">向左转</a><i class="W_vline">|</i><a action-type="feed_list_media_toRight" href="javascript:void(0);" class="turn_right">向右转</a></p>'].join(''));
  				html.push(['<div class="smallcursor" action-type="feed_list_media_bigimgDiv"><img dynamic-id="',  (new Date).getTime(), '" action-type="feed_list_media_bigimg" src="', midSrc, '" width="440"></div>'].join(''));
  				if(direct){html.push('</dd>');}
  				
  				expand.append(html.join(''));
  				expand.show();
  			}
  		}
  	}
  }
  else
  {
    $('img.imgicon').parent().trigger('click');
    if(isAdmin === true)
    {
      setInterval(function(){
          $('div.feed_preview').each(function()
          {
            if($(this).css('display') != 'none')
            {
              $(this).find('img.imgicon').parent().trigger('click');
            }
          });
        },20);
    }
  }
}

//隐藏广告
if(opt.options.ad === true)
{
    $(function(){
        $("a.close").trigger("click");
    });
}

//隐藏右边
if((isAdmin || isProfilePage) && opt.options.hide === true)
{
    $(function(){
            var rightNavs = getRightNavs(version);
           $(rightNavs).each(function(){
               if($(this).css('display') != 'none'){
               		var btnHide = '<a style="display:none;float:right;width:48px;z-index:4;" href="javascript:void(0);" i=\'i\'>隐藏</a>';
               		if(version.indexOf('3.') > -1)
               		{
               			$(this).prepend(btnHide);
	               	}else if(version == '3'){
	                   if($(this).text().indexOf('玩转微博') == -1)
	                   {
	                       $(this).prepend(btnHide);
	                   }
	                   else
	                   {
	                       $(this).find('a').parent().parent().prepend(btnHide);
	                   }
                   }
               }
           });
        

       $(rightNavs).bind('mouseenter', function(){
                       if($(this).css('display') == 'none')return;
                       if($(this).find('a[i=i]').length == 0)
                       {
                           $(this).prepend('<a style="display: none;float:right;width:48px;z-index:4;" href="javascript:void(0);" i=\'i\'>隐藏</a>');
                       }
                       var bgc = $(this).css('backgroundColor');
                       var c = 'red';
                       var obj = {'display': 'block', 'backgroundColor': bgc, 'color':c};
                       $(this).css({'border':'1px #333 solid'}).find('a[i=i]').css(obj);
                   }).bind('mouseleave', function(){
                       if($(this).css('display') == 'none')return;
                       $(this).css({'border':'0px #333 solid'}).find('a[i=i]').css('display', 'none');
                 });
         $(rightNavs).each( function(index){
                                var r = $(this);
                                if(r.css('display') == 'none')return;
                                r.find('a[i=i]').live('click', function(){
                                chrome.extension.sendRequest({'action' : 'hide', 'ele':{'pos':'right', 'index':index, 'admin':isAdmin}}, onHide);
                                r.css('display', 'none');
                                function onHide(response)
                                {
                                }
                            });
                        });
        });
	}
	
	//mute
	if(opt && opt.options && opt.options.mute === true)
	{

function muteExistsFeed()
{
    	    var feeds = getFeeds(version) || [];
	        $.each(feeds, function(index, val){
	            var text = $(val).text();
	            var muted = false;
	            $.each(muteTags, function(i, v){
	                if(v && v.length > 0 && text.indexOf(v) > -1)
	                {
	                    muted = true;
	                    $(val).remove();
	                    return false;
	                }
	            });
	        });
}
$(function()
{
        muteExistsFeed();
        
        $(document).on('scroll', function()
        {
            chrome.extension.sendRequest({'action' : 'getMuteTags'}, onGetMuteTags);
            function onGetMuteTags(t)
            {
                muteTags = t || [];
                muteExistsFeed();
            }
	    });
});
	    function getFeedRootSelector(ver)
	    {
	        var s;
	        if(ver && ver.indexOf('3.') > -1)
	        {
	            s="div.feed_lists";
	        }
	        else if(ver == '3')
	        {
	            s="#feed_list";
	        }
	        else
	        {
	            s = "div.feed_lists";
	        }
	        
	        return s;
	    }
	    function getFeedSelector(ver)
	    {
	        	        var s;
	        if(ver && ver.indexOf('3.') > -1)
	        {
	            s="div.feed_lists>dl";
	        }
	        else if(ver == '3')
	        {
	            s="#feed_list>li.MIB_linedot_l";
	        }
	        else
	        {
	            s = "div.feed_lists>dl";
	        }
	        
	        return s;
	    }
	    
	    
	    	    $(getFeedRootSelector(version)).delegate(getFeedSelector(version), 'mouseenter', function(){
	    	            if($(this).find('a[i=mute]').length == 0)
	    	            {
	    	                var btnMute = '<a style="display:none;float:right;width:48px;z-index:4;background-color:rgb(249, 242, 167);color:red;" href="javascript:void(0);" i=\'mute\'>不想再看见这条</a>';
	                        $(this).prepend(btnMute);
	                    }
	                $(this).find('a[i=mute]').css('display', '');
	             })
	            .delegate(getFeedSelector(version), 'mouseleave', function(){
	                $(this).find('a[i=mute]').css('display', 'none');
	            });
	    function getFeedIdAttr(ver)
	    {
	        	        	        var s;
	        if(ver && ver.indexOf('3.') > -1)
	        {
	            s='mid'
	        }
	        else if(ver == '3')
	        {
	            s='id'
	        }
	        else
	        {
	            s='mid'
	        }
	        
	        return s;
	    }
	    
	    function getFeedIdSelector(ver, id)
	    {
	        	        	        var s;
	        if(ver && ver.indexOf('3.') > -1)
	        {
	            s=['dl[mid=', id, ']'].join('');
	        }
	        else if(ver == '3')
	        {
	            s=['li[id=', id, ']'].join('');
	        }
	        else
	        {
	            s=['dl[mid=', id, ']'].join('');
	        }
	        
	        return s;
	    }
	    
	        $('a[i=mute]').live('click', function()
	        {
	            var mid = $(this).parent().attr(getFeedIdAttr(version));
	            popupAddTag(mid);
	        });
	        
	    function popupAddTag(feedMid)
	    {
	        if($('#cutsDesc').length == 0)
	            {
	                var cuts = [];
	                cuts.push('<div style=\'display:none;position:absolute;z-index:99998;background-color: black;\' id=cutsDesc>');
	                cuts.push('</div>');
	                cuts.push('<span id=cutsContent style=\'background-color: white;opacity:1;z-index:99999;padding:6px\'>');
	                cuts.push('<font style="font-size: 25px; color: #000000; font-weight: bold; background-color: #00FFFF;">用一两个词（Tag）<br/>说明不想看见的原因<br/>用空格分隔</font>');
	                cuts.push('<a id=\'closeCuts\' style=\'background-color:rgb(249, 242, 167);color:red;float:right;cursor:pointer\' title=\'关掉这个\'>关掉这个</a><br/><br/><br/>');
	                cuts.push('<input type=\'text\' id=\'txtMuteTags\' maxlength=\'12\' style=\'width:260px\' />');
	                cuts.push('<input type=\'button\' id=\'btnSaveMuteTags\' value=\'保存\' style=\'width:50px;height:30px\' disabled />');
	                cuts.push('</span>');
	                $('body').append(cuts.join(''));
	            }
	            $('#cutsDesc').css({height:$('body').height(), width:$('body').width(), top:'0px', left:'0px', "opacity":"0.6"}).show();
	            var windowWidth = document.documentElement.clientWidth;
                var windowHeight = document.documentElement.clientHeight;
                var popupHeight = $("#cutsContent").height();
                var popupWidth = $("#cutsContent").width();
                //centering
                $('#cutsContent').css({
                    "position": "absolute",
                    "top": windowHeight/2-popupHeight/2,
                    "left": windowWidth/2-popupWidth/2
                }).show();
                window.scrollTo(0, $('#cutsContent').scrollTop());
                
                function hideMutePopup()
                {
                    $('#cutsContent').hide();
                    $('#cutsDesc').hide();
                    $('#txtMuteTags').val('');
                    $('#closeCuts').attr('disabled', true);
                }
                
                $('#closeCuts').click(function()
                {
                    hideMutePopup();
                });
                
                
                $('#txtMuteTags').focus().on('keydown blur change', function()
                {
                    var disabledSave = true;
                    if($(this).val().trim().length > 0)
                    {
                        disabledSave = false;
                    }
                    
                    if(!disabledSave)
                    {
                        $('#btnSaveMuteTags').removeAttr('disabled');
                    }
                    else
                    {
                        $('#btnSaveMuteTags').attr('disabled', true);
                    }
                });
                
                $('#btnSaveMuteTags').click(function()
                {
                    var tags = $('#txtMuteTags').val().trim();
                    if(tags.length > 0)
                    {
                        chrome.extension.sendRequest({'action' : 'mute', 'tags':tags }, onMute);
                        function onMute(result)
                        {
                            if(result == 'success')
                            {
                                var selector = getFeedIdSelector(version, feedMid);
                                $(selector).remove();
                                hideMutePopup();
                            }
                        }
                    }
                });
	    }
	}//mute
});

